<template>
  <div class="app-container page-wood-purchase-order">
    <el-row :gutter="10" class="sumbit-btn-group mb8">
      <template v-if="!orderId">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="savePurchaseOrder"
            v-hasPermi="['woodPurchase:woodPurchaseIn:add']"
            >保存并新增</el-button
          >
        </el-col>
        <template v-if="form.orderStatus != 3">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="savePurchaseOrder(1)"
              v-hasPermi="['woodPurchase:woodPurchaseIn:edit']"
              >保存</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <Import
              :api="$Api.woodPurchase.order.import"
              @success="importSuccess"
            />
          </el-col>
        </template>
      </template>
      <template v-else>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="newAddOrder"
            >新增</el-button
          >
        </el-col>
        <template v-if="form.orderStatus != 3">
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="setAuditStatus(1)"
              >{{ form.auditStatus == 1 ? "反审核" : "审核" }}</el-button
            >
          </el-col>
        </template>
        <template v-if="form.auditStatus != 1">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="updatePurchaseOrder"
              v-hasPermi="['woodPurchase:woodPurchaseIn:edit']"
              >保存</el-button
            >
          </el-col>
        </template>
      </template>
      <template v-if="form.auditStatus == 1">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleCloseOpen"
            >{{ form.orderStatus == 3 ? "开启" : "关闭" }}</el-button
          >
        </el-col>
      </template>
      <template v-if="form.auditStatus == 1 && form.orderStatus != 3">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="purchasingSystem"
            >采购入库</el-button
          >
        </el-col>
      </template>
    </el-row>

    <div class="table-area">
      <el-form
        :model="form"
        ref="form"
        :inline="true"
        v-show="showSearch"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="供应商" prop="supplierName">
          <SupplierSelect
            v-model="form.supplierName"
            placeholder="请输入供应商"
            :disabled="disabled"
          />
        </el-form-item>

        <el-form-item label="单据日期" prop="invoicesTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.invoicesTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择单据日期"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="订单号" prop="orderId">
          <el-input
            v-model="form.orderId"
            placeholder="请输入订单号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            :disabled="orderEdit"
          />
        </el-form-item>
        <el-form-item label="开证合同" prop="pactNum">
          <el-input
            v-model="form.pactNum"
            placeholder="请输入开证合同"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="开证公司" prop="pactName">
          <SupplierSelect
            v-model="form.pactName"
            placeholder="请输入供应商"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="币别" prop="currency">
          <el-select
            v-model="form.currency"
            :disabled="disabled"
            placeholder="请选择币别"
          >
            <el-option
              v-for="item in baseCurrencyList"
              :key="item.basicsId"
              :label="item.baseCode"
              :value="item.baseCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款条件" prop="paymentClause">
          <el-select
            v-model="form.paymentClause"
            :disabled="disabled"
            placeholder="请选择付款条件"
          >
            <el-option
              v-for="item in paymentInfoList"
              :key="item.basicsId"
              :label="item.basicsName"
              :value="item.basicsName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交货方式" prop="deliveryType">
          <el-input
            v-model="form.deliveryType"
            placeholder="请输入 CIF/CFR"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="港口" prop="harbor">
          <el-select
            v-model="form.harbor"
            :disabled="disabled"
            placeholder="请选择港口"
          >
            <el-option
              v-for="item in portList"
              :key="item.basicsId"
              :label="item.basicsName"
              :value="item.basicsName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="装运日期" prop="shippingTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.shippingTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择装运日期"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="含THC" prop="isThc">
          <el-checkbox v-model="form.isThc" label="含THC" border></el-checkbox>
        </el-form-item>

        <!-- 表格开始 -->
        <TableForm
          ref="TableForm"
          :list="form.woodPurchaseOrderGoodsList"
          :renderData="tableFormOrder"
          :summary="true"
          :loading="loading"
          :disabled="disabled"
        />
        <!-- 表格结束 -->

        <!-- 备注信息 -->
        <el-form-item class="form-remark" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入备注信息"
            v-model="form.remark"
            clearable
            size="small"
            rows="5"
          />
        </el-form-item>
        <img
          v-if="form.auditStatus == 1 && form.orderStatus != 3"
          :src="img.audit"
          class="img-audit"
        />
        <img v-if="form.orderStatus == 3" :src="img.close" class="img-audit" />
      </el-form>
    </div>

  </div>
</template>

<script>

import SupplierSelect from "@/components/SupplierSelect";
import TableForm from "@/components/TableForm";
import getOrderData from "./purchaseOrderTable";

export default {
  name: "PurchaseOrder",
  components: {
    SupplierSelect,
    TableForm,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 表单参数
      form: {
        auditStatus: 0,
        isStatus: "",
        // 采购入库信息表格数据
        woodPurchaseOrderGoodsList: [
          {
            goodsName: "", // 商品名称
            brandName: "", // 品牌名称
            level: "", // 等级
            warehouse: "", // 仓位
            ply: 0, // 厚度
            width: 0, // 宽度
            length: 0, // 长度
            sliceCount: 0, // 片数
            inCount: 0, // 入库方数
            wayCount: 0, // 在途方数
            buyCount: 0, // 采购方数
            price: "", // 单价
            money: "", // 金额
            warehouse: "", //仓库
            remark: "", // 备注
            goodStatus: "", //订单商品状态
          },
        ],
      },
      // 表单校验
      rules: {
        supplierName: [
          { required: true, message: "供应商不能为空", trigger: "blur" },
        ],
        invoicesTime: [
          { required: true, message: "单据日期不能为空", trigger: "blur" },
        ],
        pactNum: [
          { required: true, message: "开证合同不能为空", trigger: "blur" },
        ],
        shippingTime: [
          { required: true, message: "装运日期不能为空", trigger: "blur" },
        ],
        currency: [
          { required: true, message: "币别不能为空", trigger: "blur" },
        ],
      },
      // 业务员
      salesman: null,
      // 各选择框数据，
      select: {
        goodsName: [],
        productName: [],
        levelName: [],
        warehouseName: [],
      },
      // 基础数据列表
      baseCurrencyList: [],
      paymentInfoList: [],
      portList: [],
      woodSupplierList: [],
      // 供应商ID
      supplierId: null,
      // 输入订单号禁止
      orderEdit: false,
      //订单号
      orderId: null,

      tableFormOrder: [],

      img: {
        audit: require("@/assets/images/bg@audit.png"),
        close: require("@/assets/images/bg@closed.png"),
      },
    };
  },
  created() {
    let { id } = this.$route.params;
    this.orderId = id;
    id && this.getPurchaseOrderDetail();

    // 获取币别
    this.$store.dispatch("getEnum", "baseCurrency").then((res) => {
      this.baseCurrencyList = res
    });
    // 获取港口
    this.$store.dispatch("getEnum", "woodPort").then((res) => {
      this.portList = res
    });
    // 获取付款条件
    this.$store.dispatch("getEnum", "paymentInfo").then((res) => {
      this.paymentInfoList = res
    });
    this.tableFormOrder = getOrderData(this);
  },
  computed: {
    disabled() {
      if (this.form.auditStatus == 1) {
        return !!this.orderId;
      }
    },
  },

  methods: {
    
    // 金额计算 ： 单价 * 方数  
    moneyCount(d) {
      let {buyCount, price } = d
      let t = ((price || 0) * (buyCount || 0)).toFixed(3)
      d.money = t
      },
    // 获取详情
    getPurchaseOrderDetail() {
      let { orderId } = this;
      this.$Api.woodPurchase.order.detail(orderId).then((res) => {
        let { data, code } = res;
        if (code === 200) {
          data.woodPurchaseOrderGoodsList = JSON.parse(
            JSON.stringify(data.woodPurchaseOrderGoodsList)
          );
          this.form = data;
          this.orderEdit = true;
        }
      });
    },
    // 检查woodPurchaseOrderGoodsList中某两个值是否相同
    checkSame(i, a, b) {
      let _a = this.form.woodPurchaseOrderGoodsList[i][a];
      let _b = this.form.woodPurchaseOrderGoodsList[i][b];
      return _a != _b;
    },

    // 表格重置
    reset() {
      this.form.woodPurchaseOrderGoodsList = [
        {
          goodsName: null, // 商品名称
          brandName: null, // 品牌名称
          level: null, // 等级
          warehouse: null, // 仓位
          ply: null, // 厚度
          width: null, // 宽度
          length: null, // 长度
          sliceCount: null, // 片数
          pieceCount: null, // 件数
          // oneCount: null, // 单包方数
          buyCount: null, // 方数
          price: null, // 单价
          money: null, // 金额
          goodsState: null, // 货物状态
          originPlace: null, // 产地
          sourceOrder: null, // 源单号
          remark: null, // 备注
        },
      ];
    },

    getFormTableData() {
      let woodPurchaseOrderList = [];
      this.form.woodPurchaseOrderGoodsList.map((item, index) => {
        woodPurchaseOrderList.push(item);
      });
      this.form.isThc = true ? "1" : "0";
      this.form.woodPurchaseOrderGoodsList = woodPurchaseOrderList;
    },
    /** 保存提交按钮 */
    savePurchaseOrder(show) {
      this.getFormTableData();
      let { orderId } = this;
      this.$refs["form"].validate((pass, error) => {
        pass &&
          this.$refs["TableForm"].checkForm((tableFormPass, error) => {
            if (tableFormPass) {
              this.$Api.woodPurchase.order.add(this.form)
                .then((res) => {
                  if (res.code == 200) {
                    this.msgSuccess("保存并新增成功");
                    if (show == 1) {
                      this.orderId = res.data;
                    }
                    // this.reset()
                    const id = this.orderId;
                    let path = `/purchase/purchaseOrder/list/${id}`;
                    this.$router.push({
                      path,
                    });
                    this.form.orderId = null;
                    this.form.pactNum = null;
                  } else {
                    this.$message.error("保存并新增失败");
                  }
                })
                .catch(() => {});
            }
          });
      });
    },
    // 新增
    newAddOrder() {
      this.$router.push({ path: "/purchase/invoice/order" });
      this.resetForm("form");
      this.reset();
    },

    // 审核与反审核 审核状态;0未审核 1已审核
    setAuditStatus(state) {
      let { orderId } = this;
      let { auditStatus } = this.form;
      let setStatus = auditStatus == 0 ? '审核' : '反审核'
      this.$confirm(
        "是否确认" +
          `${state == 2 ? "保存" : setStatus}` +
          '采购订单信息编号为"' +
          orderId +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
      .then( ()=>{
            let naxtStatus = auditStatus == 0 ? 1 : 0;
            this.$Api.woodPurchase.order.setState({
                  orderIds: [orderId],
                  orderStatus: naxtStatus,
                  isStatus: 0,
                })
                .then( (res)=>{
                    let { code } = res;
                    if( code == 200 ) {
                        this.getPurchaseOrderDetail();
                        this.msgSuccess( `${auditStatus == "0" ? '审核' : '反审核'}`+"成功");
                    }
                })
        }).catch( ()=>{}) 

    },
    // 修改订单信息
    updatePurchaseOrder(){
      let { orderId } = this;
      this.$confirm(
        "是否确认保存采购订单信息编号为" +
          orderId +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
           this.$Api.woodPurchase.order.update(this.form).then((res) => {
            if (res.code == 200) {
              this.getPurchaseOrderDetail();
              this.msgSuccess("保存成功");
            } else {
              this.$message({
                message: "操作失败",
                type: "warning",
              });
            }
          });
        }).catch(() => {});
    },
    // 订单关闭、开启订单操作 0未入库 1部分入库 2全部入库 3已关闭
    handleCloseOpen() {
      let { orderId } = this;
      let ids = [];
      ids.push(orderId);
      let { orderStatus } = this.form;
      this.$confirm(
        "是否确认" +
          `${orderStatus == "3" ? "开启" : "关闭"}` +
          '采购订单编号为"' +
          ids +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
      .then( ()=>{
            this.$Api.woodPurchase.order.setState({
                  orderIds: ids,
                  orderStatus,
                  isStatus: 1,
                })
                .then( (res)=>{
                    let { code } = res;
                    if( code == 200 ) {
                        this.getPurchaseOrderDetail();
                        this.msgSuccess(`${orderStatus == "0" ? "关闭" : "开启"}` + "成功");
                    }
                })
        }).catch( ()=>{}) 

    },
    // 采购入库按钮操作
    purchasingSystem() {
      const orderId = this.form.orderId;
      let path = `/purchase/invoice/putInstorage?orderId=${orderId}`;
      this.$router.push({
        path,
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除采购入库信息编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
      .then( ()=>{
            this.$Api.woodPurchase.order.del(supplierIds)
                .then( (res)=>{
                    let { code } = res;
                    if( code == 200 ) {
                        this.getList();
                        this.msgSuccess("删除成功");
                    }
                })
            }).catch( ()=>{})

    },
    // 导入
    importSuccess(res) {
      let { data } = res
        if(data) {
          data.woodPurchaseOrderGoodsList = data
          this.form.woodPurchaseOrderGoodsList = data
        }

    },

  },
};
</script>

<style lang="scss" scoped>
::v-deep.page-wood-purchase-order {
  .img-audit {
    position: absolute;
    right: 30px;
    bottom: 30px;
    transform: rotate(-18deg);
    pointer-events: none;
  }
  .sumbit-btn-group {
    margin: 0 0 20px 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }

  .disabled {
    color: #a8a8a8;
  }

  .error {
    color: #fa3e3e;
  }
  .form-remark {
    display: grid;
    margin: 20px 15px 15px;
    .el-form-item__contentt {
      display: inline-block;
      width: 100%;
    }
  }
}
</style>